package P123_VolatileNoDataSync;

/**
 * volatile 不能保证数据同步
 *
 * @author xufy1
 */
public class ValatileNoDataSync {

    /**
     * volatile 不能保证多线程安全，只能保证当前线程获得主内存的最新值
     * 1. java1.5 volatile不同系统表现不一样，移植性差
     * 2. 使用难，误用多
     */
//    @Test
    public static void main(String[] args) throws InterruptedException {

        int value = 1000;
        int loops = 0;
        ThreadGroup tg = Thread.currentThread().getThreadGroup();
        while (loops++ < value) {
            UnsafeThread ut = new UnsafeThread();
            for (int i = 0; i < value; i++) {
                new Thread(ut).start();
            }
            /*do {
                Thread.sleep(15);
            } while (tg.activeCount() != 1);*/
            if (ut.getCount() != value) {
                System.out.println("循环到第 " + loops + " 遍，出现线程不安全情况");
                System.out.println("此时， count=" + ut.getCount());
                System.exit(0);
            }
        }
    }


}

class UnsafeThread implements Runnable {
    private volatile int count = 0;

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            Math.hypot(Math.pow(6, i), Math.cos(i));
        }
        count++;
    }

    public int getCount() {
        return count;
    }
}
